#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import os
import json
import time
import logging
from PIL import Image, ImageDraw, ImageFont

# 路径配置
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')
if os.path.exists(libdir):
    sys.path.append(libdir)
from waveshare_epd import epd7in5_V2

# 显示配置
FONT_PATH = os.path.join(picdir, 'Font.ttc')  # 字体文件路径
DATA_FILE = "env_data.json"

class EPaperDisplay:
    def __init__(self):
        self.epd = epd7in5_V2.EPD()
        self.font_large = ImageFont.truetype(FONT_PATH, 40)
        self.font_medium = ImageFont.truetype(FONT_PATH, 30)
        self.font_small = ImageFont.truetype(FONT_PATH, 20)
        
    def initialize(self):
        """初始化屏幕"""
        self.epd.init()
        self.epd.Clear()
        logging.info("墨水屏初始化完成")

    def display_sensor_data(self):
        """显示传感器数据"""
        try:
            # 读取数据文件
            with open(DATA_FILE, 'r') as f:
                data = json.load(f)
            
            # 创建画布
            image = Image.new('1', (self.epd.width, self.epd.height), 255)
            draw = ImageDraw.Draw(image)
            
            # 绘制标题
            draw.text((20, 10), "环境监测数据", font=self.font_large, fill=0)
            
            # 绘制数据行
            y_position = 70
            self._draw_data_row(draw, "温度:", f"{data['temp']}℃", y_position)
            y_position += 60
            self._draw_data_row(draw, "湿度:", f"{data['humidity']}%", y_position)
            y_position += 60
            self._draw_data_row(draw, "气压:", f"{data['pressure']}hPa", y_position)
            
            # 添加分隔线
            draw.line((20, y_position+20, 780, y_position+20), fill=0, width=2)
            
            # 显示时间戳
            timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            draw.text((500, y_position+40), f"更新时间: {timestamp}", font=self.font_small, fill=0)
            
            # 更新显示
            self.epd.display(self.epd.getbuffer(image))
            
        except FileNotFoundError:
            self._show_error("数据文件未找到")
        except json.JSONDecodeError:
            self._show_error("数据格式错误")
        except KeyError as e:
            self._show_error(f"数据字段缺失: {str(e)}")

    def _draw_data_row(self, draw, label, value, y):
        """绘制数据行"""
        # 标签
        draw.text((50, y), label, font=self.font_medium, fill=0)
        # 数值
        draw.text((250, y-5), value, font=self.font_large, fill=0)

    def _show_error(self, message):
        """显示错误信息"""
        image = Image.new('1', (self.epd.width, self.epd.height), 255)
        draw = ImageDraw.Draw(image)
        draw.text((50, 200), "错误:", font=self.font_large, fill=0)
        draw.text((50, 250), message, font=self.font_medium, fill=0)
        self.epd.display(self.epd.getbuffer(image))

    def sleep(self):
        """进入低功耗模式"""
        self.epd.sleep()

def main():
    logging.basicConfig(level=logging.INFO)
    
    # 初始化显示设备
    display = EPaperDisplay()
    try:
        display.initialize()
        while True:
            display.display_sensor_data()
            time.sleep(300)  # 5分钟刷新一次
    except KeyboardInterrupt:
        display.sleep()
        logging.info("安全关闭屏幕")
    except Exception as e:
        logging.error(f"运行时错误: {str(e)}")
        display.sleep()

if __name__ == "__main__":
    main()

